<script setup lang="ts">
import dayjs from 'dayjs'
import { getCertListApi } from '@/apis/modules/cert'
import { certListOptions, LicenseSourceOptions } from '@/constants/cdn-node'
import { commonTableProps } from '@/utils/table'
import ApplyLog from '../../cert-detail/dialogs/ApplyLog.vue'
import useConfig from './useConfig'

const router = useRouter()
const { tableColumns, searchSchema } = useConfig()
const appList = computed<OptionItem[]>(() => {
  return useAppStore().appList || []
})
const queryParams = ref({
  app_id: '',
  // expired_at_gte: '',
  // expired_at_lte: '',
})

const {
  loading,
  data: tableData,
  pagination,
  run,
} = useListRequest(getCertListApi, {
  params: queryParams,
  immediate: true,
})

// 删除
// function handleDelete(id: string) {
//   ModalHelper.error({
//     title: '删除证书',
//     content: '确定要删除该证书么？该记录将从列表中移除。',
//     okText: '删除',
//     width: 480,
//     closable: false,
//     onOk: async () => {
//       await deleteCertApi({ ids: [id] })
//       await run()
//       Message.success('删除成功')
//     },
//   })
// }

function toManagement(row: any) {
  router.push({ name: 'CertDetail', params: { id: row.id } })
}
const { visible: logVisible, open: openLog, data: logData } = usePopup()

async function handleOpenLog(record: any) {
  // const res = await getLog(record.id!)
  // if (res)
  openLog(record.latest)
}

const { createSortChange } = useTable(run, tableData)
const onSorterChange = createSortChange(queryParams)
function FirstDomain(domains: string) {
  if (!domains || domains.trim() === '') {
    return { domain: null, length: 0 }
  }
  const parts = domains.split(',')
  const domain = parts[0] || ''
  const length = parts.length - 1
  return { domain, length }
}

const dateRange = ref<string[]>([])
watch(dateRange, () => {
  const [start, end] = dateRange.value || []
  queryParams.value.expired_at_gte = start || ''
  queryParams.value.expired_at_lte = end ? (Number(end) + 86400).toString() : ''
  run()
})
</script>

<template>
  <main-container
    v-model:pagination="pagination"
    :loading="loading"
    @run="run"
  >
    <div class="mb-4 flex justify-between">
      <a-select
        v-model="queryParams.app_id"
        :options="[{ label: '全部应用', value: '' }, ...appList]"
        placeholder="请选择所属应用"
        class="mr-4 !w-[136px]"
        @change="run()"
      />
      <multiple-condition-search
        v-model="queryParams"
        :schema="searchSchema"
        @search="run"
      />
      <a-button
        class="ml-auto shrink-0 text-color-1"
        type="outline"
        :disabled="loading"
        @click="run"
      >
        <template #icon>
          <i-icons-refresh :class="{ 'animate-spin': loading }" />
        </template>
      </a-button>
    </div>

    <a-table
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="tableData"
      @sorter-change="onSorterChange"
    >
      <template #domain="{ record }">
        <div class="flex items-center">
          <span
            style="
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            "
          >{{ FirstDomain(record.domain).domain || '-' }}</span>
          <div
            v-if="FirstDomain(record.domain).length > 0"
            class="domains-length-tag"
          >
            {{ FirstDomain(record.domain).length }}
          </div>
        </div>
      </template>
      <template #appId="{ record }">
        <div>
          <span>{{ getOptionsLabel(appList, record.app_id) }}</span>
        </div>
      </template>
      <template #source="{ record }">
        <div>
          <span>{{
            getOptionsLabel(LicenseSourceOptions, record.source)
          }}</span>
        </div>
      </template>
      <template #auto_renew="{ record }">
        <div v-if="record.source === 1">
          不支持
        </div>
        <div v-else>
          <span>
            {{ record.auto_renew ? '已开启' : '已关闭' }}
          </span>
        </div>
      </template>
      <template #updated_at="{ record }">
        <div class="flex">
          <span
            style="
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            "
          >
            {{
              dayjs(record.latest.created_at * 1000).format(
                'YYYY-MM-DD HH:mm:ss',
              )
            }}</span>
          <div class="ml-1 min-w-4">
            <a-tooltip
              :show-arrow="false"
              content="查看日志"
            >
              <i-icons-log
                class="table-icon"
                size="16px"
                @click="handleOpenLog(record)"
              />
            </a-tooltip>
          </div>
        </div>
        <div>
          <span
            :class="
              record.latest?.status === 1
                ? 'text-#86909C'
                : record.latest?.status === 2
                  ? 'text-#FA5566'
                  : 'text-#00A65B'
            "
          >{{ getOptionsLabel(certListOptions, record.latest?.status) }}</span>
        </div>
      </template>
      <template #expired_at="{ record }">
        <div class="flex">
          <span
            style="
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            "
          >
            <span v-if="record.expired_at !== '0'">{{
              dayjs(record.expired_at * 1000).format('YYYY-MM-DD HH:mm:ss')
            }}</span>
            <span v-else>-</span>
          </span>
        </div>
        <div>
          <span v-if="record?.expired_at === '0'" />
          <div v-else>
            <span
              v-if="calculateRemainingDays(record?.expired_at || 0) > 0"
              class="text-#86909C"
            >{{
              calculateRemainingDays(record?.expired_at || 0)
            }}天后过期</span>
            <span
              v-if="calculateRemainingDays(record?.expired_at || 0) < 0"
              class="text-#FA5566"
            >已过期</span>
          </div>
        </div>
      </template>
      <template #actions="{ record }">
        <a-tooltip
          :show-arrow="false"
          content="管理"
        >
          <a-link
            :hoverable="false"
            @click="toManagement(record)"
          >
            <i-icons-application size="16px" />
          </a-link>
        </a-tooltip>
      </template>
    </a-table>
  </main-container>

  <apply-log
    v-model:visible="logVisible"
    v-model:record="logData"
    @refresh-row="row => handleRefreshRow(row)"
  />
</template>

<style scoped>
.domains-length-tag {
  color: var(--text-2, #4e5969);

  /* regular/12 */
  font-family: 'Microsoft YaHei UI';
  font-size: 12px;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
  display: flex;
  height: 16px;
  padding: 0px 6px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 10px;
  border-radius: 9999px;
  border: 1px solid var(--border-2, #e5e6eb);
  background: var(--fill-1, #f7f8fa);
  margin-left: 4px;
}
:deep(.arco-table-tr) {
  .table-icon {
    opacity: 0;
    color: var(--color-text-7);
    cursor: pointer;
  }

  &:hover {
    .table-copy-text {
      @apply text-primary;
    }

    .table-icon {
      opacity: 1;
      color: #00a65b;
    }
  }
}
</style>
